<template>
  <div class="change-trading-dialog-view">

    <el-dialog
        v-model="dialogVisible"
        :before-close="handleClose"
        title="变更交易精细招商信息"
        width="1100px"
    >
      <item-title title="选择变更后使用的新产品与价格"/>

      <el-form
          label-width="110px"
      >
        <el-form-item label="选择交易产品">
          <!--                    <div style="display: flex;width: 800px">-->
          <!--                        <product-popover :searchs="productPopularName" @confirm="productConfirm">-->
          <!--                            <el-input v-model="productPopularName" placeholder="请输入产品名称" @blur="onBlur" style="width: 500px"/>-->

          <!--                        </product-popover>-->

          <!--&lt;!&ndash;                        <span style="padding-left: 20px">仅可添加同一产品下的交易终端</span>&ndash;&gt;-->
          <!--                    </div>-->

          <el-select v-model="formData.productId" placeholder="请选择交易产品" style="width: 100%" @change="productChange">
            <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

      </el-form>

      <el-form
          ref="refForm"
          :inline="true"
          :model="formData"
          :rules="rules"
          class="info-form"
          label-width="110px"
      >
        <el-row>

          <el-col :span="12">
            <el-form-item label="营销模式" prop="sellMode">
              <el-select v-model="formData.sellMode" placeholder="请选择营销模式" style="width: 100%" @change="modeChange">
                <el-option v-for="item in salesModel" :key="item.id" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col v-if="formData.sellMode !== 'direct'" :span="12">
            <el-form-item label="代理商名称" prop="agentName">
              <el-autocomplete
                  v-model="formData.agentName"
                  :fetch-suggestions="querySearchAsyncAgent"
                  placeholder="请输入代理商名称"
                  style="width: 100%"
                  @select="handleSelectAgent"
              >
                <template #default="{ item }">
                  <div class="distributeName">{{ item.agentName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交易价" prop="tradePrice">
              <!--                            <el-input v-if="formData.sellMode === 'direct'" v-model="formData.tradePrice" clearable-->
              <!--                                      placeholder="请输入交易价">-->
              <!--                                <template #append>-->
              <!--                                    <span>元</span>-->
              <!--                                </template>-->
              <!--                            </el-input>-->
              <template v-if="formData.sellMode === 'direct'">
                <price-input
                    v-model:data="formData.tradePrice"
                    :unit-str="'元/' + unit"
                    is-unit
                    placeholder="请输入交易价"
                />
              </template>
              <template v-else>
                <app-trading-popover
                    ref="agentPop"
                    :props-agent="formData"
                    @confirm="agentConfirm"
                >
                  <el-select
                      v-model="formData.tradePrice"
                      placeholder="请选择交易价"
                      style="width: 100%"
                      @clear="agentClear"
                      @focus="agentFocus"
                  >
                    <template #empty/>
                  </el-select>
                </app-trading-popover>
              </template>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="负责营销职员" prop="headId">
              <el-select v-model="formData.headId" placeholder="请选择营销职员" style="width: 100%" @change="handlChangeHead">
                <el-option v-for="item in headList" :key="item.id" :label="item.realName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="最低销量" prop="minSale">
              <el-input v-model.number="formData.minSale" clearable placeholder="请输入最低销量">
                <template #append>
                  <span v-if="unit" style="margin-right: 10px">{{ unit }}/</span>
                  <el-select v-model="formData.minSaleUnit" placeholder="请选择" style="width: 80px;">
                    <el-option v-for="item in nuitData" :key="item.id" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量保证金" prop="sellEarnestMoney">
              <el-input v-model="formData.sellEarnestMoney" clearable placeholder="请输入销量保证金"/>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>

      <item-title title="选择此代理商下的交易终端"/>

      <div style="margin-bottom: 10px">

        <el-button type="primary" @click="addTerminalClick">添加终端</el-button>

        <el-button type="primary" @click="allRemove">全部移除</el-button>

      </div>

      <el-table
          :data="tableData"
          border
          max-height="250"
          style="margin-bottom: 10px"
      >
        <el-table-column align="center" header-align="center" label="终端编号" prop="terminalNo" show-overflow-tooltip
                         width="100"/>
        <el-table-column align="left" header-align="center" label="终端名称" prop="terminalName" show-overflow-tooltip/>
        <el-table-column align="center" header-align="center" label="所在地区" show-overflow-tooltip width="100">
          <template #default="{row}">
            <span>{{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" header-align="center" label="产品信息" prop="productInfoDetail.productPopularName"
                         show-overflow-tooltip width="150"/>
        <el-table-column align="center" header-align="center" label="终端价(元)" width="100">
          <template #default="scope">
            {{ scope.row.terminalPrice }}
          </template>
        </el-table-column>

        <el-table-column align="center" header-align="center" label="当前交易价(元)" width="100">
          <template #default="scope">
            {{ scope.row.tradePrice }}
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="当前代理产品与价格编号" show-overflow-tooltip width="100">
          <template #default="scope">
            <span v-if="scope.row.productPriceStrategyDetail">{{
                scope.row.productPriceStrategyDetail.priceNumber
              }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" label="操作" width="100">
          <template #default="scope">
            <el-button
                type="text"
                @click.stop="onRemoved(scope)"
            >移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="dialogConfirm">提交审核</el-button>
        </div>
      </template>

    </el-dialog>

    <add-terminal-dialog ref="addTerminal" :area="areas" :datas="formData" @confirm="onConfirm"/>

  </div>
</template>

<script>
import {getScreenAreaData} from '@/utils/areaFuc.js'
import area from '@/utils/area.js'
import {crmStore} from '@CRM/store'
import addTerminalDialog from './addTerminalDialog.vue'
import {defineComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs} from 'vue'

export default defineComponent({
  name: 'ChangeTradingDialog',
  components: {addTerminalDialog},
  props: {
    agent: {
      type: Object,
      default: {}
    }
  },
  setup(props, {emit}) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const salesModel = crmStore.getters['dictionary/getDictionary']['agentType']
    const nuitData = crmStore.getters['dictionary/getDictionary']['sell_num_unit']
    const rules = ref({
      agentName: [{required: true, message: '请选择代理商名称', trigger: 'blur'}],
      tradePrice: [{required: true, message: '请输入交易价', trigger: 'blur'}],
      headId: [{required: true, message: '请选择代负责人', trigger: 'change'}]
    })

    var data = reactive({
      dialogVisible: false,
      formData: {
        sellMode: '',
        agentName: '',
        agentId: 0,
        tradePrice: '',
        agentProductId: 0,
        headName: '',
        headId: null,
        minSale: 0,
        minSaleUnit: '1',
        sellEarnestMoney: 0,
        productId: '',
        productPopularName: '',
        terminalType: '',
        region: []
      },
      productPopularName: '',
      productId: '',
      tableData: [],
      selectProduct: {},
      addTerminal: null,
      agentPop: null,
      refForm: null,
      headList: [],
      productList: [],
      areas: [],
      unit: ''
    })

    const modeChange = () => {
      data.formData.tradePrice = 0
      data.formData.terminalType = ''
      data.formData.agentProductId = 0
      data.formData.agentId = 0
      data.formData.agentName = ''
      data.formData.region = []
      data.tableData = []
      if (data.formData.sellMode == 'direct') {
        data.areas = area
      } else {
        data.areas = []
      }
    }

    const productConfirm = (val) => {
      if (data.tableData.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请先移除全部终端',
        })
        return
      }

      console.log(val)
      data.selectProduct = val
      data.formData.productId = val.id
      data.productPopularName = val.productPopularName + '/' + val.approvalNumber + '/' + val.packSpecs
    }

    const productChange = (val) => {
      if (val) {
        const index = data.productList.findIndex(a => a.id == val)
        if (index != -1) {
          data.selectProduct = data.productList[index]
          data.formData.productPopularName = data.selectProduct.productPopularName
          data.unit = currentInstance.proxy.getLabel('sell_unit', data.selectProduct.sellUnit)
        }
      } else {
        data.selectProduct = null
        data.unit = ''
      }

      data.formData.agentProductId = ''
      data.formData.tradePrice = ''
      data.formData.region = []
      data.formData.terminalType = ''
      data.areas = []
      data.formData.minSale = 0
      data.formData.minSaleUnit = '1'
      data.formData.sellEarnestMoney = 0
      data.tableData = []
    }

    const onBlur = () => {
      if (data.selectProduct.id) {
        data.productPopularName = data.selectProduct.productPopularName + '/' + data.selectProduct.approvalNumber + '/' + data.selectProduct.packSpecs
      }
    }

    const onConfirm = (list) => {
      const a = []
      let str = ''
      for (let i = 0; i < list.length; i++) {
        const index = data.tableData.findIndex(a => a.id == list[i].id)
        if (index == -1) {
          a.push(list[i])
        } else {
          if (str) {
            str = str + ','
          }
          str = str + list[i].terminalName
        }
      }

      if (str) {
        currentInstance.proxy.customMessage({
          type: 'warning',
          message: str + '已添加',
        })
      }

      data.tableData = data.tableData.concat(a)
    }

    const allRemove = () => {
      data.tableData = []
    }

    const onRemoved = (scope) => {
      data.tableData.splice(scope.$index, 1)
    }

    // 获取代理商列表
    const querySearchAsyncAgent = async (queryString, cb) => {
      const a = {
        agentType: data.formData.sellMode,
        keyWord: queryString,
      }
      let results = []
      const res = await api.terminal.REGISTERED_TERMINAL_CHANNEL(a)
      if (!res.code && res.data) {
        results = res.data.list
      }
      cb(results)
    }

    // 代理商事件
    const handleSelectAgent = (val) => {
      data.formData.agentId = val.id
      data.formData.agentName = val.agentName

      data.formData.agentProductId = 0
      data.formData.tradePrice = ''
    }

    // 交易价
    const agentConfirm = (val) => {
      console.log(val)
      data.formData.agentProductId = val.id
      data.formData.tradePrice = val.tradePrice
      data.formData.region = val.region
      data.formData.terminalType = val.terminalType
      data.formData.minSale = val.minSale
      data.formData.minSaleUnit = val.minSaleUnit
      data.formData.sellEarnestMoney = val.minSalePromise
      data.areas = getScreenAreaData(data.formData.region)
    }

    // 打开交易价弹框
    const agentFocus = (val) => {
      if (val) {
        data.agentPop.openPopover()
      }
    }

    // 取消交易价弹框
    const agentClear = () => {
      data.formData.agentProductId = 0
      data.formData.tradePrice = ''
    }

    const handleClose = () => {
      data.formData.region = []
      data.formData.productId = ''
      data.refForm.resetFields()
      setTimeout(() => {
        data.tableData = []
        data.dialogVisible = false
        data.refForm.clearValidate()
      }, 100)
    }

    const dialogConfirm = () => {
      if (!data.tableData.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择终端',
        })
        return
      }
      if (data.formData.tradePrice) {
        for (let i = 0; i < data.tableData.length; i++) {
          const item = data.tableData[i]
          if (data.formData.tradePrice > item.terminalPrice) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '交易价不能大于终端价',
            })
            return
          }
        }
      }

      data.refForm.validate(val => {
        if (val) {
          const a = {...data.formData}
          a.sellEarnestMoney = Number(a.sellEarnestMoney)
          a.ids = []
          data.tableData.forEach(item => {
            a.ids.push(item.id)
          })

          api.signedAgent.RELATIONSTANDARD_SET_NEW_AGENT_PRICE(a).then(res => {
            if (!res.code) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '提交成功',
              })

              emit('success')

              handleClose()
            }
          })
        }
      })
    }

    const openDialog = () => {
      data.dialogVisible = true
    }

    const addTerminalClick = () => {
      if (!data.formData.productId) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择产品',
        })
        return
      }

      if (data.formData.sellMode != 'direct') {
        console.log(data.formData)
        if (!data.formData.agentId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择代理商',
          })
          return
        }
        if (!data.formData.agentProductId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择交易价',
          })
          return
        }
      }

      data.addTerminal.openDialog()
    }

    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then(res => {
        if (res.code === 0) {
          data.headList = res.data
        }
      })
    }

    // 负责人事件
    const handlChangeHead = (val) => {
      const index = data.headList.findIndex(a => a.id === val)
      if (index !== -1) {
        data.formData.headName = data.headList[index].realName
      }
    }

    onMounted(_ => {
      handlHead()
      if (props.agent.agentType) {
        data.formData.sellMode = props.agent.agentType
      }
      if (props.agent.id) {
        data.formData.agentId = props.agent.id
        data.formData.agentName = props.agent.agentName
      }

      api.signedAgent.AGENTPRODUCT_PRODUCT_LIST(props.agent.id).then(res => {
        if (!res.code && res.data) {
          res.data.agentProduct.forEach(item => {
            item.name = item.productPopularName + '/' + item.approvalNumber + '/' + item.packSpecs
          })

          data.productList = res.data.agentProduct
        }
      })
    })

    return {
      ...toRefs(data),
      salesModel,
      nuitData,
      rules,

      handleClose,
      dialogConfirm,
      openDialog,
      productConfirm,
      onBlur,
      addTerminalClick,
      onConfirm,
      allRemove,
      querySearchAsyncAgent,
      handleSelectAgent,
      agentConfirm,
      agentFocus,
      agentClear,
      handlChangeHead,
      modeChange,
      onRemoved,
      productChange,
    }
  }
})
</script>

<style lang="scss" scoped>
.change-trading-dialog-view {
  .info-form {
    .el-form-item {
      width: 100%;
    }
  }
}

</style>
